import json,time
from django.db.models.aggregates import Sum
from django.http import HttpResponse,JsonResponse
from website_server.models import ArticleTab, AttentionTab, IslikeTab, LoginTab, SystemInforms, TopicsTab,UserinfoTab
from django.forms.models import model_to_dict
from website_server.utils import CJsonEncoder, getID, getTime, http_post,log_in, model_to_list
from channels.generic.websocket import WebsocketConsumer

# Create your views here.
# 注册账号
@http_post
def register(request):
  try:
    rq = request.POST
    username = rq['username']
    password = rq['password']
    if LoginTab.objects.filter(username=rq['username']).first():
      return HttpResponse('用户名已存在')
    login = LoginTab()
    login.username,login.password,login.root,login.time= username,password,0,time.strftime("%Y-%m-%d", time.localtime())
    login.save() 
    user_info = UserinfoTab()
    user_info.username = LoginTab.objects.get(username=username)
    user_info.picture = '/static/image/picture/用户头像.png'
    user_info.save()
    return HttpResponse(1)
  except Exception as err:
    print(err)
    return HttpResponse('服务器繁忙!')

# 登陆
@http_post
def login(request):
  rq = request.POST
  try:
    username = rq.get('username')
    password = rq.get('password')
    if username and password:
      result = LoginTab.objects.filter(username=rq.get('username'),password=rq.get('password')).first()
      if result:
        request.session['user'] = rq.get('username')
        request.session.set_expiry(0)
        return HttpResponse(userInfo(request))
      else:
        return HttpResponse('用户名或密码错误')
    else:
      if request.session.get('user',False):
        return HttpResponse(userInfo(request))
      else:
        return HttpResponse('登录过期!')
  except Exception:
    return HttpResponse('请求异常!')
   

# 获取用户个人信息
@http_post
def userInfo(request):
  try:
    username = request.POST.get('userName',False) or request.session.get('user')
    result = {
      **model_to_dict(UserinfoTab.objects.get(username=username)),
      'token': request.session.session_key
    }
    return JsonResponse(result)
  except Exception:
    return HttpResponse('系统异常')

@log_in
# 修改个人信息
def updateUserInfo(request):
  try:
    rq = request.POST
    userinfo = UserinfoTab.objects.get(username=request.session['user'])
    userinfo.name = rq['name']
    userinfo.age = rq['age']
    userinfo.sex = rq['sex']
    userinfo.constellation = rq['constellation']
    userinfo.birthday = rq['birthday']
    userinfo.save()
    return JsonResponse(rq)
  except Exception:
    return HttpResponse('登陆已过期')

# 退出登陆
def exitLogin(request):
  del request.session['user']
  return HttpResponse(1)

# 上传头像
@log_in
def uploadPicture(request):
  try:
    username = request.session['user']
    userinfo = UserinfoTab.objects.get(username=username)
    file = request.FILES.get('picture')
    path = 'static/image/picture/' + username + '.' + file.name.split('.')[-1]
    with open(path, 'wb') as f:
      for content in file.chunks():
        f.write(content)
    userinfo.picture = '/' + path
    userinfo.save()
    return HttpResponse('/' + path)
  except Exception as err:
    print(err)
    return HttpResponse(err)

# 获取用户相关数据
@http_post
def getUserData(request):
  rq = request.POST
  if rq.get('username') != None:
    username = rq.get('username')
    user_article_list = [x['articleid'] for x in ArticleTab.objects.filter(username=username).values('articleid')]
    userData = {
      'topicsCount': TopicsTab.objects.filter(username=username).count(),
      'articleCount': ArticleTab.objects.filter(username=username).count(),
      'siteAge': LoginTab.objects.get(username=username).time,
      'visitCount': TopicsTab.objects.filter(username=username).aggregate(Sum('visit')).get('visit__sum'),
      'likeCount': IslikeTab.objects.filter(articleid__in=user_article_list).count(),
      'attentionCount': AttentionTab.objects.filter(onusername=username).count(),
      'isAttention': AttentionTab.objects.filter(nusername=request.session.get('user'),onusername=username).exists()
    }
    userinfo = {**model_to_dict(UserinfoTab.objects.get(username=username)),**userData}
    return JsonResponse({'data': userinfo})
  else:
    return HttpResponse('用户不存在')

# 查看系统消息
@log_in
def lookInforms(request):
  rq = request.POST
  id = rq.get('id')
  if id:
    informs = SystemInforms.objects.filter(informsid=id).first()
    if informs:
      informs.islook = 1
      informs.save()
      return JsonResponse(model_to_dict(informs))
    else:
      return HttpResponse('消息不存在')
  else:
    return HttpResponse('参数错误')

# 删除已读系统消息
@log_in
def removeSystemInforms(request):
  username = request.session.get('user')
  if username:
    SystemInforms.objects.filter(username=username,islook=1).delete()
    return HttpResponse(1)
  else:
    return HttpResponse('删除失败')

# 关注用户
@log_in
def attentionUser(request):
  rq = request.POST
  username= rq.get('username')
  try:
    if username:
      attention = AttentionTab()
      attention.attentionid = getID()
      attention.nusername = UserinfoTab.objects.get(username=request.session.get('user'))
      attention.onusername = UserinfoTab.objects.get(username=username)
      attention.time = getTime()
      attention.save()
      return HttpResponse(1)
    else:
      return HttpResponse('用户不存在!')
  except:
    return HttpResponse('参数错误')

# 消息通知
class messageQueue(WebsocketConsumer):
  def connect(self):
    self.accept()

  def disconnect(self,code):
    pass

  def receive(self,text_data=None):
    username = self.scope['session']['user']
    if not username:
      self.close()
    else:
      informs = SystemInforms.objects.filter(username=username).order_by('-time')
      if informs.first():
        self.send(text_data=json.dumps({'data': model_to_list(informs)},cls=CJsonEncoder))
      else:
        self.send(text_data=json.dumps({'message': '暂无消息'}))